package com.whfc.common.aviator;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author sun_guodong
 * @description 表达式工具
 * @date 2020-12-09
 */
public class AviatorUtil {
    private static Logger logger = LoggerFactory.getLogger(AviatorUtil.class);

    public static Boolean checkValue(String expression, Map<String, Object> param) {
        Boolean result = null;
        try {
            // 编译表达式
            Expression compiledExp = AviatorEvaluator.compile(expression);
            // 执行表达式
            result = (Boolean) compiledExp.execute(param);
        } catch (Exception e) {
            logger.error("表达式或者参数错误", e);
        }
        return result;
    }


    /**
     * 检测设备倾斜报警
     *
     * @return
     */
    public static String checkMachRotationWarn(Double rotationX, Double rotationZ, String ruleValue) {
        Map<String, Object> env = new HashMap<>();
        env.put("rotationX", rotationX);
        env.put("rotationZ", rotationZ);
        env.put("machRotationRule", ruleValue);
        AviatorEvaluator.addFunction(new MachRotationWarnCheckFunction());
        String result = (String) AviatorEvaluator.execute("machRotationWarnCheck(rotationX,rotationZ,machRotationRule)", env);
        return result;
    }

    public static void main(String[] args) {
        String expression = "a-(b-c)>100";
        Map<String, Object> env = new HashMap<>();
        env.put("a", 100.3);
        env.put("b", 45);
        env.put("c", 45);

        String ruleValue = "{\"preRotationX\":6,\"postRotationX\":6,\"leftRotationZ\":3,\"rightRotationZ\":10}";
        System.out.println(checkMachRotationWarn(32D, 35D, ruleValue));

        Boolean b = AviatorUtil.checkValue(expression, env);
        System.out.println(b);
    }

}
